#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/mman.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#define WIDTH  640
#define HEIGHT 480

int main() {
    // Allocate buffer for image data
    int stride = WIDTH * 4;
    u_int8_t *image_data = malloc(stride * HEIGHT);
    if (!image_data) {
        fprintf(stderr, "Failed to allocate image buffer\n");
        return 1;
    }
    // Fill with red (ARGB: 0xFFFF0000, XRGB: 0x00FF0000)
    for (int y = 0; y < HEIGHT; ++y) {
        u_int32_t *row = (u_int32_t *)(image_data + y * stride);
        for (int x = 0; x < WIDTH; ++x) {
            row[x] = 0x00FF0000;
        }
    }

    // X11 part
    Display *dpy = XOpenDisplay(NULL);
    if (!dpy) {
        fprintf(stderr, "Failed to open X display\n");
        return 1;
    }

    int screen = DefaultScreen(dpy);
     Window win = XCreateSimpleWindow(dpy, RootWindow(dpy, screen), 0, 0, WIDTH, HEIGHT, 1,
                                     BlackPixel(dpy, screen), WhitePixel(dpy, screen));
    XImage *image = XCreateImage(dpy, DefaultVisual(dpy, screen), DefaultDepth(dpy, screen),
                                  ZPixmap, 0, (char *)image_data, WIDTH, HEIGHT, 32, stride);
    XFlush(dpy);

    // Create a Pixmap and copy BO data to it
    // Clean up
    XDestroyImage(image);
    //XFreePixmap(dpy, pixmap);
    XDestroyWindow(dpy, win);
    XCloseDisplay(dpy);
    free(image_data);

    return 0;
}
